import React, { useState } from 'react';
import { Form, Button, Modal, Select, Upload,Radio,message } from 'antd';
import { FormValueType, TreeNode } from '../data.d';
import { LoadingOutlined, PlusOutlined } from '@ant-design/icons';
import {  addDict } from '@/services/dict';
import styles from '../style.less';
const { Option } = Select;
const FormItem = Form.Item;
import CreateTypeForm from '@/pages/authority/dict/components/CreateForm';
export interface CreateFormProps {
  modalVisible: boolean;
  typeValues:API.DictItem[];
  onSubmit: (values: FormValueType,resetForm: any) => void;
  onCancel: () => void;
  reloadType: () => void;
  removeImage: () => void;
}

const formLayout = {
  labelCol: { span: 5 },
  wrapperCol: { span: 18 },
};

const formLayout1 = {
  labelCol: { span: 6 },
  wrapperCol: { span: 17 },
};

/**
 * 添加节点
 * @param fields
 */
 const addDictCode = async (fields: any) => {
  const hide = message.loading('正在添加');
  try {
    await addDict(fields);
    hide();
    message.success('添加成功');
    return true;
  } catch (error) {
    hide();
    message.error('添加失败请重试！');
    return false;
  }
};
const CreateForm: React.FC<CreateFormProps> = (props) => {
  const { modalVisible, onSubmit: handleAdd, onCancel,typeValues,reloadType,removeImage} = props;
  const [createTypeModalVisible, handleTypeModalVisible] = useState<boolean>(false);
  const [formVals, setFormVals] = useState<FormValueType>({
    drawingId:'',
    useState: 1,
  });

  const [form] = Form.useForm();
  const [loading, setLoading] = useState<boolean>(false);
  const [fileList, setFileList] = useState<Array<object>>([]);
  const [previewImage, setPreviewImage] = useState<string>();
  const [previewVisible, setPreviewVisible] = useState<boolean>(false);
  const [previewTitle, setPreviewTitle] = useState<string>();
  const [typeId, setTypeId] = useState<string>('');
  const [duseState, setDUseState] = useState<number>(1);
  const okHandle = async () => {
  let ids="";
    const fieldsValue = await form.validateFields();
    for(let item of fileList){
      ids+=",'"+item.response.drawingId+"'";
    }
    fieldsValue.drawingId= formVals.drawingId;
    fieldsValue.ids= ids.substring(1);
    console.log(fieldsValue)
    form.resetFields();
   handleAdd(fieldsValue,resetForm);
};

  const resetForm= async () => {
    form.resetFields();
  };
  const handlePreview = async file => {
    console.log(file)
    // if (!file.url && !file.preview) {
    //   file.preview = file.response.path;
    // }

    setPreviewImage(file.response.path);
    setPreviewVisible(true);
    setPreviewTitle(file.response.drawingName);
   
  };

 
  const handleChange = (info: any) => {
    setFileList(info.fileList)
    if (info.file.status === 'uploading') {
      setLoading(true);
      return;
    }
    console.log(info.file);
    if (info.file.status === 'done') {
      console.log(info.file.response)
      // Get this url from response in real world.
      const file = info.file.response;
      console.log(file)
     
      setFormVals({ ...formVals, ...file });
      setLoading(false);
    }
  };

  const beforeUpload = (file: any) => {
    
    const isJpgOrPng = file.type === 'image/jpeg' || file.type === 'image/png';
       console.log(file)
    if (!isJpgOrPng) {
      message.error('只能上传JPG/PNG文件!');
    
    }
   
    const isLt2M = file.size / 1024 / 1024 < 2;
    if (!isLt2M) {
      message.error('图像必须小于2MB!');
    }
    return isJpgOrPng && isLt2M?true: Upload.LIST_IGNORE;
  }

  const uploadButton = (
    <div>
      {loading ? <LoadingOutlined /> : <PlusOutlined />}
      <div className="ant-upload-text">上传图纸</div>
    </div>
  );
  const fileDoc=function (){
    if(formVals.suffix=="jpg"||formVals.suffix=="jpeg"||formVals.suffix=="png"){
      return ( <img src={ formVals.relativePath} alt="avatar" style={{ width: '100%' }} />)
    }else{
      return ( 
        <div>
          <div className="ant-upload-text">{formVals.title}</div>
        </div>)
    }
  }   
  return (
    <div>
    <Modal
      width={640}
      maskClosable={false}
      destroyOnClose
      title="新增图纸"
      visible={modalVisible}
      footer={<div ><button type="button" class="ant-btn" onClick={onCancel} ><span>取 消</span></button><button type="button" onClick={okHandle} disabled={loading}  class="ant-btn ant-btn-primary"><span>确 定</span></button></div>}
      // onOk={okHandle}
      onCancel={() => onCancel()}
    >
      <Form
      
        form={form}
        initialValues={formVals}
      >     
        <div style={{    display: 'flex'}}>
          <div     style={{  width: '490px'}} >
          <FormItem
            label="图纸分类"
            name="typeId"
            {...formLayout1}
            rules={[{ required: true, message: '请选择图纸分类！' }]}

          >
            <Select placeholder="请选择图纸分类" onChange={(value)=>setTypeId(value)}>
                {typeValues.map((item) => (
                    <Option key={item.dictCode} value={item.dictCode}>
                    {item.dictValue}
                  </Option>
              ))}
            </Select> 
          </FormItem>
        </div>
           <Button type="primary"  onClick={async () => {  handleTypeModalVisible(true)  }}  >新增分类</Button>
          </div>
        <FormItem
          {...formLayout}
          label="图纸"
          name="attachCode"
          rules={[{ required: true, message: '请选上传图纸' }]}
        >
        <Upload
                name="file"
                listType="picture-card"
                //showUploadList={false}
                className={styles.uploader}
                data={{typeId}}
                action="/api/drawingfileUpload"
                // beforeUpload={beforeUpload}
                onPreview={handlePreview}
                onChange={handleChange}
                onRemove ={(value)=>removeImage(value.response.drawingId)}
              >
                {fileList.length >=9 ? null : uploadButton}
                {/* {formVals.relativePath ? fileDoc() : uploadButton} */}
              </Upload>
        </FormItem>
        
      </Form>
    </Modal>
       <CreateTypeForm
         onSubmit={async (value) => {
          const success = await addDictCode(value);
          if (success) {
            handleTypeModalVisible(false);
            reloadType();
          }
        }}
        onCancel={() => handleTypeModalVisible(false)}
        modalVisible={createTypeModalVisible}
        typeId={3}
        typeName={'图纸分类'}
       
       ></CreateTypeForm>

         <Modal
          visible={previewVisible}
          title={previewTitle}
          footer={null}
          onCancel={ () => setPreviewVisible(false)}
        >
          <img alt="example" style={{ width: '100%' }} src={previewImage} />
        </Modal>
       </div>
    
  );
};

export default CreateForm;
